const usermodel = require('../db/user')
const {resinfo} = require('../utlis/utlis')
const {renameSync} = require('fs')
const path = require('path')
const svgCaptcha = require('svg-captcha')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const nodemailer = require('nodemailer')
const transport = nodemailer.createTransport({
    "host": "smtp.163.com",
    "port": 465,
    "secure": true,
    auth: {
        user: '15777755613@163.com',
        pass: 'UTEKHAMOFXOEJUIQ'
    }
})

module.exports = {

    // 验证码获取
    reglogCode:async(req,res)=>{
        let captcha = svgCaptcha.create()
        res.cookie('captcha',captcha.text,{
            maxAge:3600*1000,
          })
        res.type('svg');
        res.send(captcha.data);
    },

    // 注册
    register: async (req, res) => {
        let {username, password, tel,email} = req.body
        let url = null
        if(!username||!password||!tel) {
            resinfo(res, 1, '数据不能为空')
            return
        };
        var res1 = await usermodel.find({username})
        if(res1.length) {
            resinfo(res, 3, '用户名被占用')
            return
        };
        var res2 = await usermodel.find({tel})
        if(res2.length) {
            resinfo(res, 3, '手机号已被注册')
            return
        };
        var res3 = await usermodel.find({email})
        if(res3.length) {
            resinfo(res, 3, '该邮箱已被注册')
            return
        };
        var res4 = await usermodel.insertMany({
            username,
            password: bcrypt.hashSync(password, 10),
            tel,
            email,
            url
        });
        if(res4.length) {
            resinfo(res, 0, '注册成功')
        } else {
            resinfo(res, 2, '注册失败，请刷新后重试')
        }
    },

    // 登录
    login:async(req,res)=>{
        let {username,password} = req.body
        if(!username||!password){
            resinfo(res,1,'数据不能为空')
            return
        }
        let userinfo =await usermodel.find({username})
        if(!userinfo.length){
            resinfo(res,3,'用户名或密码错误')
            return
        }
        let userPassword = userinfo[0].password
        let bool = bcrypt.compareSync(password,userPassword)
        if(bool&&userinfo.length){
            let token = jwt.sign({
                username:username,
                startTime: +new Date(),
                expires: 7200*1000
            },'asdsdf')
            resinfo(res,0,'登录成功',{token,userid:userinfo[0]._id})
            return
        }else{
            resinfo(res,3,'用户名或密码错误')
            return
        }
    },

    // 获取用户信息
    userInfo:async(req,res)=>{

         let userid = req.params.id
         let userInfo
         try{
            userInfo = await usermodel.findOne({
                _id:userid
            })
         }catch(err){
            resinfo(res,1,'用户信息获取失败')
            return
        }
        resinfo(res,0,'用户信息获取成功',{userInfo})

    },

    // 用户信息修改
    userEdit:async(req,res)=>{
        let userid = req.params.id
        let {username, tel} = req.body
        var res1 = await usermodel.find({username})
        if(res1.length) {
            resinfo(res, 3, '用户名被占用')
            return
        };
        var res2 = await usermodel.find({tel})
        if(res2.length) {
            resinfo(res, 3, '手机号已被绑定，每个手机号只能绑定一个用户！')
            return
        };
        try{
        await usermodel.updateOne({_id:userid},{$set:{username,tel}})
          resinfo(res,0,'修改成功')
        }catch(err){
            resinfo(res,1,'修改失败')
        }

    },

    // 密码修改
    userpass:async(req,res)=>{
        let userid = req.params.id
        let {newpassword,password} = req.body
        let userData     
        try{
            userData = await usermodel.find({
                _id:userid
            })
        }catch(err){
            resinfo(res,1,'用户id有误')
            return
        }

        //  验证密码
        let bool =  bcrypt.compareSync(password,userData[0].password)

        if(bool){
            try{
                await usermodel.updateMany({
                    _id:userid
  
                },{$set:{
                    password:bcrypt.hashSync(newpassword,10)
                }})
            }catch(err){

                resinfo(res,2,'修改失败')
                return
            }
            resinfo(res,0,'修改成功,请重新登录。')
        }else{
            resinfo(res,2,'修改失败，请刷新后重试。')
            return
        }
    },

    // 头像修改
    userhead:async(req,res)=>{
        let extname = path.extname(req.file.originalname)
        renameSync(req.file.path,req.file.path+extname)
        let userid = req.params.id
        let url = req.file.filename+extname
        try{
            await usermodel.updateOne({_id:userid},{$set:{url}})
              resinfo(res,0,'修改成功')
            }catch(err){
                resinfo(res,1,'修改失败请刷新后重试')
            }
    },

    // 邮箱发送验证码
    userEmail:async(req,res)=>{
        let captcha = svgCaptcha.create()
        let{Email} = req.body
        res.cookie('vcatcode',bcrypt.hashSync(captcha.text, 10),{
            maxAge:600*1000,
          })
        transport.sendMail({
            from: '15777755613@163.com',
            to: Email,
            subject: '验证码',
            html: `
                该验证码十分钟内有效，复制该验证码：
                <br>
                ${captcha.text}
            `
        }, function(err) {
            if(err) {
                resinfo(res,2,'发送失败')
                return
            }
            resinfo(res,0,'发送成功')
        })
    },

    // 确认验证码
    confirmcode:async(req,res)=>{
        let{reglogCode,vcatcode,email} = req.body
        let userInfo = await usermodel.find({email})
        let bool =  bcrypt.compareSync(reglogCode,vcatcode)  
        if(!bool){
            resinfo(res,2,'验证码错误，请重新确认！')
        }else{
            resinfo(res,0,'验证通过！',{userid:userInfo[0]._id})
        }
    },

    // 找回密码
    loadpasss:async(req,res)=>{
        let userid = req.params.id
        let{password} = req.body
        try{
            await usermodel.updateOne({_id:userid},{$set:{
                password:bcrypt.hashSync(password,10)
            }})
              resinfo(res,0,'修改成功')
            }catch(err){
                resinfo(res,1,'修改失败')
            }
    }

}